/**
 * 学术研究自动化平台 - 前端JavaScript
 */

// 全局配置
const App = {
    config: {
        apiBaseUrl: '/api',
        csrfToken: null,
        currentUser: null
    },
    
    // 初始化
    init: function() {
        this.setupCSRF();
        this.setupAjaxDefaults();
        this.setupGlobalEventHandlers();
        this.setupTooltips();
        this.setupAnimations();
        console.log('学术研究自动化平台已初始化');
    },
    
    // 设置CSRF令牌
    setupCSRF: function() {
        const csrfToken = $('meta[name="csrf-token"]').attr('content');
        if (csrfToken) {
            this.config.csrfToken = csrfToken;
            $.ajaxSetup({
                beforeSend: function(xhr, settings) {
                    if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) {
                        xhr.setRequestHeader("X-CSRFToken", csrfToken);
                    }
                }
            });
        }
    },
    
    // 设置Ajax默认配置
    setupAjaxDefaults: function() {
        $.ajaxSetup({
            timeout: 30000,
            cache: false,
            error: function(xhr, status, error) {
                if (xhr.status === 401) {
                    App.showAlert('会话已过期，请重新登录', 'warning');
                    setTimeout(() => {
                        window.location.href = '/login';
                    }, 2000);
                } else if (xhr.status === 403) {
                    App.showAlert('权限不足', 'danger');
                } else if (xhr.status >= 500) {
                    App.showAlert('服务器错误，请稍后重试', 'danger');
                } else if (status === 'timeout') {
                    App.showAlert('请求超时，请检查网络连接', 'warning');
                }
            }
        });
    },
    
    // 设置全局事件处理器
    setupGlobalEventHandlers: function() {
        // 表单验证
        $('form[data-validate="true"]').on('submit', function(e) {
            if (!App.validateForm($(this))) {
                e.preventDefault();
                return false;
            }
        });
        
        // 确认对话框
        $('[data-confirm]').on('click', function(e) {
            const message = $(this).data('confirm');
            if (!confirm(message)) {
                e.preventDefault();
                return false;
            }
        });
        
        // 自动保存
        $('[data-autosave]').on('input change', App.debounce(function() {
            App.autoSave($(this));
        }, 1000));
        
        // 文件上传预览
        $('input[type="file"][data-preview]').on('change', function() {
            App.previewFile(this);
        });
        
        // 搜索功能
        $('[data-search]').on('input', App.debounce(function() {
            App.performSearch($(this));
        }, 300));
    },
    
    // 设置工具提示
    setupTooltips: function() {
        $('[data-bs-toggle="tooltip"]').tooltip();
        $('[data-bs-toggle="popover"]').popover();
    },
    
    // 设置动画
    setupAnimations: function() {
        // 页面加载动画
        $('.fade-in').each(function(index) {
            $(this).delay(index * 100).animate({
                opacity: 1
            }, 600);
        });
        
        // 滚动动画
        $(window).on('scroll', App.throttle(function() {
            App.handleScrollAnimations();
        }, 100));
    },
    
    // 显示警告消息
    showAlert: function(message, type = 'info', duration = 5000) {
        const alertId = 'alert-' + Date.now();
        const alertHtml = `
            <div id="${alertId}" class="alert alert-${type} alert-dismissible fade show position-fixed" 
                 style="top: 20px; right: 20px; z-index: 9999; min-width: 300px;" role="alert">
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        `;
        
        $('body').append(alertHtml);
        
        // 自动消失
        if (duration > 0) {
            setTimeout(() => {
                $(`#${alertId}`).alert('close');
            }, duration);
        }
        
        return alertId;
    },
    
    // 显示加载状态
    showLoading: function(element, text = '加载中...') {
        const $element = $(element);
        const originalContent = $element.html();
        
        $element.data('original-content', originalContent);
        $element.html(`
            <span class="spinner-border spinner-border-sm me-2" role="status"></span>
            ${text}
        `).prop('disabled', true);
        
        return function() {
            $element.html(originalContent).prop('disabled', false);
        };
    },
    
    // 隐藏加载状态
    hideLoading: function(element) {
        const $element = $(element);
        const originalContent = $element.data('original-content');
        
        if (originalContent) {
            $element.html(originalContent).prop('disabled', false);
        }
    },
    
    // 表单验证
    validateForm: function($form) {
        let isValid = true;
        
        // 清除之前的错误
        $form.find('.is-invalid').removeClass('is-invalid');
        $form.find('.invalid-feedback').remove();
        
        // 验证必填字段
        $form.find('[required]').each(function() {
            const $field = $(this);
            const value = $field.val().trim();
            
            if (!value) {
                App.showFieldError($field, '此字段为必填项');
                isValid = false;
            }
        });
        
        // 验证邮箱格式
        $form.find('input[type="email"]').each(function() {
            const $field = $(this);
            const value = $field.val().trim();
            
            if (value && !App.isValidEmail(value)) {
                App.showFieldError($field, '请输入有效的邮箱地址');
                isValid = false;
            }
        });
        
        // 验证密码强度
        $form.find('input[data-password-strength]').each(function() {
            const $field = $(this);
            const value = $field.val();
            
            if (value && !App.isStrongPassword(value)) {
                App.showFieldError($field, '密码必须包含大小写字母、数字和特殊字符，至少8位');
                isValid = false;
            }
        });
        
        return isValid;
    },
    
    // 显示字段错误
    showFieldError: function($field, message) {
        $field.addClass('is-invalid');
        $field.after(`<div class="invalid-feedback">${message}</div>`);
    },
    
    // 邮箱验证
    isValidEmail: function(email) {
        const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return regex.test(email);
    },
    
    // 密码强度验证
    isStrongPassword: function(password) {
        const minLength = 8;
        const hasLower = /[a-z]/.test(password);
        const hasUpper = /[A-Z]/.test(password);
        const hasNumber = /\d/.test(password);
        const hasSpecial = /[!@#$%^&*(),.?":{}|<>]/.test(password);
        
        return password.length >= minLength && hasLower && hasUpper && hasNumber && hasSpecial;
    },
    
    // 自动保存
    autoSave: function($element) {
        const url = $element.data('autosave');
        const data = {};
        data[$element.attr('name')] = $element.val();
        
        $.ajax({
            url: url,
            method: 'POST',
            data: JSON.stringify(data),
            contentType: 'application/json',
            success: function() {
                App.showSaveIndicator($element, true);
            },
            error: function() {
                App.showSaveIndicator($element, false);
            }
        });
    },
    
    // 显示保存指示器
    showSaveIndicator: function($element, success) {
        const indicator = success ? 
            '<i class="fas fa-check text-success"></i>' : 
            '<i class="fas fa-times text-danger"></i>';
        
        const $indicator = $(indicator).insertAfter($element);
        
        setTimeout(() => {
            $indicator.fadeOut(() => $indicator.remove());
        }, 2000);
    },
    
    // 文件预览
    previewFile: function(input) {
        const file = input.files[0];
        const $preview = $($(input).data('preview'));
        
        if (file) {
            const reader = new FileReader();
            
            reader.onload = function(e) {
                if (file.type.startsWith('image/')) {
                    $preview.html(`<img src="${e.target.result}" class="img-fluid" alt="预览">`);
                } else {
                    $preview.html(`
                        <div class="text-center p-3">
                            <i class="fas fa-file fa-3x text-muted mb-2"></i>
                            <p class="mb-0">${file.name}</p>
                            <small class="text-muted">${App.formatFileSize(file.size)}</small>
                        </div>
                    `);
                }
            };
            
            reader.readAsDataURL(file);
        } else {
            $preview.empty();
        }
    },
    
    // 格式化文件大小
    formatFileSize: function(bytes) {
        if (bytes === 0) return '0 Bytes';
        
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    },
    
    // 搜索功能
    performSearch: function($input) {
        const query = $input.val().trim();
        const target = $input.data('search');
        
        if (query.length < 2) {
            $(target).show();
            return;
        }
        
        $(target).each(function() {
            const text = $(this).text().toLowerCase();
            const match = text.includes(query.toLowerCase());
            $(this).toggle(match);
        });
    },
    
    // 滚动动画处理
    handleScrollAnimations: function() {
        $('.animate-on-scroll').each(function() {
            const $element = $(this);
            const elementTop = $element.offset().top;
            const elementBottom = elementTop + $element.outerHeight();
            const viewportTop = $(window).scrollTop();
            const viewportBottom = viewportTop + $(window).height();
            
            if (elementBottom > viewportTop && elementTop < viewportBottom) {
                $element.addClass('animated');
            }
        });
    },
    
    // 防抖函数
    debounce: function(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    },
    
    // 节流函数
    throttle: function(func, limit) {
        let inThrottle;
        return function() {
            const args = arguments;
            const context = this;
            if (!inThrottle) {
                func.apply(context, args);
                inThrottle = true;
                setTimeout(() => inThrottle = false, limit);
            }
        };
    },
    
    // API调用封装
    api: {
        get: function(url, data = {}) {
            return $.ajax({
                url: App.config.apiBaseUrl + url,
                method: 'GET',
                data: data
            });
        },
        
        post: function(url, data = {}) {
            return $.ajax({
                url: App.config.apiBaseUrl + url,
                method: 'POST',
                data: JSON.stringify(data),
                contentType: 'application/json'
            });
        },
        
        put: function(url, data = {}) {
            return $.ajax({
                url: App.config.apiBaseUrl + url,
                method: 'PUT',
                data: JSON.stringify(data),
                contentType: 'application/json'
            });
        },
        
        delete: function(url) {
            return $.ajax({
                url: App.config.apiBaseUrl + url,
                method: 'DELETE'
            });
        }
    },
    
    // 工具函数
    utils: {
        // 格式化日期
        formatDate: function(date, format = 'YYYY-MM-DD HH:mm:ss') {
            const d = new Date(date);
            const year = d.getFullYear();
            const month = String(d.getMonth() + 1).padStart(2, '0');
            const day = String(d.getDate()).padStart(2, '0');
            const hours = String(d.getHours()).padStart(2, '0');
            const minutes = String(d.getMinutes()).padStart(2, '0');
            const seconds = String(d.getSeconds()).padStart(2, '0');
            
            return format
                .replace('YYYY', year)
                .replace('MM', month)
                .replace('DD', day)
                .replace('HH', hours)
                .replace('mm', minutes)
                .replace('ss', seconds);
        },
        
        // 相对时间
        timeAgo: function(date) {
            const now = new Date();
            const diff = now - new Date(date);
            const seconds = Math.floor(diff / 1000);
            const minutes = Math.floor(seconds / 60);
            const hours = Math.floor(minutes / 60);
            const days = Math.floor(hours / 24);
            
            if (days > 0) return `${days}天前`;
            if (hours > 0) return `${hours}小时前`;
            if (minutes > 0) return `${minutes}分钟前`;
            return '刚刚';
        },
        
        // 生成UUID
        generateUUID: function() {
            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
                const r = Math.random() * 16 | 0;
                const v = c == 'x' ? r : (r & 0x3 | 0x8);
                return v.toString(16);
            });
        },
        
        // 深拷贝
        deepClone: function(obj) {
            return JSON.parse(JSON.stringify(obj));
        },
        
        // 获取URL参数
        getUrlParam: function(name) {
            const urlParams = new URLSearchParams(window.location.search);
            return urlParams.get(name);
        }
    }
};

// 页面特定功能
const PageModules = {
    // 仪表板模块
    dashboard: {
        init: function() {
            this.loadStats();
            this.setupCharts();
            this.setupRealTimeUpdates();
        },
        
        loadStats: function() {
            App.api.get('/user/stats').done(function(data) {
                if (data.success) {
                    $('.stat-projects').text(data.stats.projects);
                    $('.stat-analyses').text(data.stats.analyses);
                    $('.stat-collaborations').text(data.stats.collaborations);
                }
            });
        },
        
        setupCharts: function() {
            // 图表初始化代码已在模板中
        },
        
        setupRealTimeUpdates: function() {
            setInterval(() => {
                this.loadStats();
            }, 30000); // 每30秒更新一次
        }
    },
    
    // 项目管理模块
    projects: {
        init: function() {
            this.setupProjectTable();
            this.setupProjectFilters();
            this.setupProjectActions();
        },
        
        setupProjectTable: function() {
            // 项目表格功能
        },
        
        setupProjectFilters: function() {
            // 项目过滤功能
        },
        
        setupProjectActions: function() {
            // 项目操作功能
        }
    }
};

// 页面加载完成后初始化
$(document).ready(function() {
    App.init();
    
    // 根据页面加载对应模块
    const page = $('body').data('page');
    if (page && PageModules[page]) {
        PageModules[page].init();
    }
});

// 导出到全局
window.App = App;
window.PageModules = PageModules;